package com.xinqi.modules.stats.studyanalysis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.common.base.response.PageInfo;
import com.xinqi.common.base.response.R;
import com.xinqi.common.core.constant.PatternConstants;
import com.xinqi.common.core.enums.ClassRoleEnum;
import com.xinqi.common.core.enums.StudyAnalysisTypeEnum;
import com.xinqi.common.mybatis.data.service.impl.BaseServiceImpl;
import com.xinqi.common.mybatis.utils.Pages;
import com.xinqi.common.satoken.utils.LoginHelper;
import com.xinqi.modules.course.clazz.client.ClassClient;
import com.xinqi.modules.course.clazz.client.ClassStudentClient;
import com.xinqi.modules.course.clazz.dto.rsp.ClassResultDTO;
import com.xinqi.modules.course.clazz.dto.rsp.ClassStudentResultDTO;
import com.xinqi.modules.course.course.client.RemoteCourseClient;
import com.xinqi.modules.course.course.dto.rsp.CourseResultDTO;
import com.xinqi.modules.stats.content.domain.CourseContentEntity;
import com.xinqi.modules.stats.studyanalysis.domain.CourseAnalysisEntity;
import com.xinqi.modules.stats.studyanalysis.dto.req.StudentAnalysisQueryDTO;
import com.xinqi.modules.stats.studyanalysis.dto.req.StudentInfoAnalysisQueryDTO;
import com.xinqi.modules.stats.studyanalysis.dto.req.StudyAnalysisExportDTO;
import com.xinqi.modules.stats.studyanalysis.dto.rsp.*;
import com.xinqi.modules.stats.studyanalysis.mapper.CourseAnalysisMapper;
import com.xinqi.modules.stats.studyanalysis.mapper.StudyAnalysisMapper;
import com.xinqi.modules.stats.studyanalysis.service.CourseAnalysisService;
import com.xinqi.modules.stats.studyanalysis.service.CourseStudentAnalysisService;
import com.xinqi.modules.stats.studyanalysis.service.StudyAnalysisService;
import com.xinqi.modules.stats.utils.ExcelUtil;
import com.xinqi.modules.stats.utils.MathUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;
import java.util.regex.Matcher;
import java.util.stream.Collectors;

/**
 * 学情分析
 * @author 刘学
 */
@Service
@RequiredArgsConstructor
public class StudyAnalysisServiceImpl extends BaseServiceImpl<StudyAnalysisMapper, CourseContentEntity> implements StudyAnalysisService {

    private final ClassStudentClient classStudentClient;

    private final CourseAnalysisService analysisService;

    private final CourseAnalysisMapper analysisMapper;

    private final CourseStudentAnalysisService studentAnalysisService;

    private final RemoteCourseClient courseClient;

    private final ClassClient classClient;

    @Override
    public List<StudyAnalysisVo> wholeAnalysis(Long classId) {

        ArrayList<StudyAnalysisVo> resultList = new ArrayList<>();

        // 校验是否需要生成数据
        this.checkCreateAnalysis(classId);

        // 查询分析数据
        StudyAnalysisStatisticsDTO res = this.baseMapper.wholeAnalysis(classId);
        if (Objects.isNull(res)) {
            res = new StudyAnalysisStatisticsDTO();
        }

        //构建作业
        StudyAnalysisVo homework = buildStudyAnalysisVo(String.valueOf(res.getHomeworkPublishNum()), StudyAnalysisTypeEnum.HOMEWORK.getCode());
        //构建测评
        StudyAnalysisVo exam = buildStudyAnalysisVo(String.valueOf(res.getExamPublishNum()), StudyAnalysisTypeEnum.EXAM.getCode());

        //构建讨论
        StudyAnalysisVo discuss = buildStudyAnalysisVo(String.valueOf(res.getDiscussPublishNum()), StudyAnalysisTypeEnum.DISCUSS.getCode());

        //构建互动课件
        StudyAnalysisVo interactiveCourse = buildStudyAnalysisVo(String.valueOf(res.getInteractieCoursePublishNum()), StudyAnalysisTypeEnum.INTERACTIVECOURSE.getCode());
        //构建互动视频
        StudyAnalysisVo interactiveVideo = buildStudyAnalysisVo(String.valueOf(res.getInteractieVideoPublishNum()), StudyAnalysisTypeEnum.INTERACTIVEVIDEO.getCode());
        //构建资料
        StudyAnalysisVo resource = buildStudyAnalysisVo(String.valueOf(res.getResoucePublishNum()), StudyAnalysisTypeEnum.RESOURCE.getCode());
        //构建测评
        StudyAnalysisVo notice = buildStudyAnalysisVo(String.valueOf(res.getNoticePublishNum()), StudyAnalysisTypeEnum.NOTICE.getCode());
        //构建测评
        StudyAnalysisVo attendence = buildStudyAnalysisVo(String.valueOf(res.getAttendancePublishNum()), StudyAnalysisTypeEnum.ATTENDENCE.getCode());

        resultList.add(homework);
        resultList.add(exam);
        resultList.add(notice);
        resultList.add(discuss);
        //resultList.add(interactiveCourse);
        resultList.add(interactiveVideo);
        resultList.add(resource);
        //resultList.add(attendence);
        return resultList;
    }

    @Override
    public Map<String, Object> studentAnalysis(StudentAnalysisQueryDTO analysisQueryDTO) {
        Long userId = LoginHelper.getUserId();
        if (analysisQueryDTO.getPageNum() == null) {
            analysisQueryDTO.setPageNum(1L);
        }
        if (analysisQueryDTO.getPageSize() == null) {
            analysisQueryDTO.setPageSize(20L);
        }
        if (StringUtils.isNotEmpty(analysisQueryDTO.getSort())) {
            String sort = analysisQueryDTO.getSort();
            String underscore = camelCaceToUnderscore(sort);
            if (!underscore.contains("whole_finished_rate")) {
                analysisQueryDTO.setOrderby(underscore);
            }
        }
        IPage<StudentAnalysisContentResultDTO> page = new Page<>(analysisQueryDTO.getPageNum(), analysisQueryDTO.getPageSize());
        Map<String, Object> result = new HashMap<>();
        //查询头部信息
        StudentAnalysisHeadResultDTO headResultDTO = this.baseMapper.studentAnalysisHead(analysisQueryDTO.getClassId());
        //查询内容信息
        IPage<StudentAnalysisContentResultDTO> contentsPage = this.baseMapper.studentAnalysisContent(page, analysisQueryDTO);
        //计算整体完成率
        List<StudentAnalysisContentResultDTO> finishedRates = calculateWholeFinishedRate(contentsPage.getRecords());
        contentsPage.setRecords(finishedRates);
        //对整体完成率排序
        List<StudentAnalysisContentResultDTO> wholeFinishedRates = sorWholeFinishedRates(contentsPage.getRecords(), analysisQueryDTO);
        contentsPage.setRecords(wholeFinishedRates);
        PageInfo<StudentAnalysisContentResultDTO> pageInfo = Pages.convert(contentsPage);
        result.put("head", headResultDTO);
        result.put("contents", pageInfo);
        return result;
    }

    @Override
    public Map<String, Object> studentInfoAnalysis(StudentInfoAnalysisQueryDTO analysisQueryDTO) {
        Long userId = LoginHelper.getUserId();
        ClassStudentResultDTO operaStudent = R.as(classStudentClient.findByStudentId(analysisQueryDTO.getClassId(), userId));
        Map<String, Object> result = new HashMap<>();
        StudentInfoAnalysisHeadResultDTO infoAnalysisHeadResultDTO = this.baseMapper.studentInfoHeadAnalysis(analysisQueryDTO);
        result.put("head", infoAnalysisHeadResultDTO);
        // 老师端查询生成数据、学生端实时数据
        if (Objects.equals(ClassRoleEnum.TEACHER.getCode(), operaStudent.getClassRole())
            || Objects.equals(ClassRoleEnum.ASSISTANT.getCode(), operaStudent.getClassRole())) {
            StudentAnalysisContentResultDTO contentsPage = this.baseMapper.teacherStudentInfoContentAnalysis(analysisQueryDTO);
            List<StudyAnalysisVo> contents = calculateFinishedRate(contentsPage);
            result.put("contents", contents);
        } else {
            ClassStudentResultDTO mainStudent = R.as(classStudentClient.findVirtualClassStudentByClassIdAndUserId(analysisQueryDTO.getClassId(), userId));
            analysisQueryDTO.setStudentId(mainStudent.getStudentId());
            StudentAnalysisContentResultDTO contentsPage = this.baseMapper.studentInfoContentAnalysis(analysisQueryDTO);
            List<StudyAnalysisVo> contents = calculateFinishedRate(contentsPage);
            result.put("contents", contents);
        }
        return result;
    }

    /**
     * @param str
     * @return java.lang.String
     * @author liuxingxing
     * @Description 将驼峰转为下划线
     * @since 1.0.0
     */
    private String camelCaceToUnderscore(String str) {
        Matcher matcher = PatternConstants.ATOZCompile.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        String result = sb.toString();
        result = result.replaceAll("\\|", " ");
        return result;
    }

    public List<StudentAnalysisContentResultDTO> calculateWholeFinishedRate(List<StudentAnalysisContentResultDTO> results) {
        if (results != null && results.size() > 0) {
            for (StudentAnalysisContentResultDTO result : results) {
                Integer sum = 0;
                Integer finishSum = 0;
                //计算总数
                Integer homeworkPublishNum = result.getHomeworkPublishNum();
                Integer examPublishNum = result.getExamPublishNum();
                Integer discussPublishNum = result.getDiscussPublishNum();
                Integer attendancePublishNum = result.getAttendancePublishNum();
                Integer interactieCoursePublishNum = result.getInteractieCoursePublishNum();
                Integer interactieVideoPublishNum = result.getInteractieVideoPublishNum();
                Integer resoucePublishNum = result.getResoucePublishNum();
                sum = homeworkPublishNum + examPublishNum + discussPublishNum + attendancePublishNum + interactieCoursePublishNum + interactieVideoPublishNum + resoucePublishNum;
                //计算完成数
                Integer homeworkFinishedNum = result.getHomeworkFinishedNum();
                Integer examFinishedNum = result.getExamFinishedNum();
                Integer discussFinishedNum = result.getDiscussFinishedNum();
                Integer interactieCourseFinishedNum = result.getInteractieCourseFinishedNum();
                Integer interactieVideoFinishedNum = result.getInteractieVideoFinishedNum();
                Integer resouceFinishedNum = result.getResouceFinishedNum();
                Integer attendanceFinishedNum = result.getAttendanceFinishedNum();
                finishSum = homeworkFinishedNum + examFinishedNum + discussFinishedNum + interactieCourseFinishedNum + interactieVideoFinishedNum + resouceFinishedNum + attendanceFinishedNum;
                String percent = calculatePercent(finishSum, sum);
                result.setWholeFinishedRate(percent);
            }
        }
        return results;
    }

    private List<StudyAnalysisVo> calculateFinishedRate(StudentAnalysisContentResultDTO result) {
        List<StudyAnalysisVo> vos = new ArrayList<>();
        //计算所有数量
        Integer sum = 0;
        Integer finishSum = 0;
        //计算总数
        Integer homeworkPublishNum = result.getHomeworkPublishNum();
        Integer examPublishNum = result.getExamPublishNum();
        Integer discussPublishNum = result.getDiscussPublishNum();
        Integer attendancePublishNum = result.getAttendancePublishNum();
        Integer interactieCoursePublishNum = result.getInteractieCoursePublishNum();
        Integer interactieVideoPublishNum = result.getInteractieVideoPublishNum();
        Integer resoucePublishNum = result.getResoucePublishNum();
        //Integer noticePublishNum = result.getNoticePublishNum();
        sum = homeworkPublishNum + examPublishNum + discussPublishNum + attendancePublishNum + interactieCoursePublishNum + interactieVideoPublishNum + resoucePublishNum;


        //作业完成率
        Integer homeworkFinishedNum = result.getHomeworkFinishedNum();
        String homeworkPercent = calculatePercent(homeworkFinishedNum, homeworkPublishNum);
        StudyAnalysisVo homeworkPercentVo = buildStudyAnalysisVo(homeworkPercent, StudyAnalysisTypeEnum.HOMEWORK.getCode());

        //测评完成率
        Integer examFinishedNum = result.getExamFinishedNum();
        String examPercent = calculatePercent(examFinishedNum, examPublishNum);
        StudyAnalysisVo examPercentVo = buildStudyAnalysisVo(examPercent, StudyAnalysisTypeEnum.EXAM.getCode());

        //讨论完成率
        Integer discussFinishedNum = result.getDiscussFinishedNum();
        String discussPercent = calculatePercent(discussFinishedNum, discussPublishNum);
        StudyAnalysisVo discussPercentPercentVo = buildStudyAnalysisVo(discussPercent, StudyAnalysisTypeEnum.DISCUSS.getCode());

        //公告页面暂时未显示
        //Integer noticeFinishedNum = result.getNoticeFinishedNum();

        //互动课件完成率
        Integer interactieCourseFinishedNum = result.getInteractieCourseFinishedNum();
        String interactieCoursePercent = calculatePercent(interactieCourseFinishedNum, interactieCoursePublishNum);
        StudyAnalysisVo interactieCoursePercentPercentVo = buildStudyAnalysisVo(interactieCoursePercent, StudyAnalysisTypeEnum.INTERACTIVECOURSE.getCode());

        //互动视频完成率
        Integer interactieVideoFinishedNum = result.getInteractieVideoFinishedNum();
        String interactieVideoPercent = calculatePercent(interactieVideoFinishedNum, interactieVideoPublishNum);
        StudyAnalysisVo interactieVideoPercentPercentVo = buildStudyAnalysisVo(interactieVideoPercent, StudyAnalysisTypeEnum.INTERACTIVEVIDEO.getCode());

        //资料完成率
        Integer resouceFinishedNum = result.getResouceFinishedNum();
        String resourcePercent = calculatePercent(resouceFinishedNum, resoucePublishNum);
        StudyAnalysisVo resourcePercentPercentVo = buildStudyAnalysisVo(resourcePercent, StudyAnalysisTypeEnum.RESOURCE.getCode());

        //出勤完成率
        Integer attendanceFinishedNum = result.getAttendanceFinishedNum();
        String attendancePercent = calculatePercent(attendanceFinishedNum, attendancePublishNum);
        StudyAnalysisVo attendancePercentVo = buildStudyAnalysisVo(attendancePercent, StudyAnalysisTypeEnum.ATTENDENCE.getCode());

        //整体完成率
        finishSum = homeworkFinishedNum + examFinishedNum + discussFinishedNum + interactieCourseFinishedNum + interactieVideoFinishedNum + resouceFinishedNum + attendanceFinishedNum;
        String wholePercent = calculatePercent(finishSum, sum);
        StudyAnalysisVo wholePercentVo = buildStudyAnalysisVo(wholePercent, StudyAnalysisTypeEnum.WHOLE.getCode());

        vos.add(wholePercentVo);
        vos.add(homeworkPercentVo);
        vos.add(examPercentVo);
        vos.add(discussPercentPercentVo);
        //vos.add(interactieCoursePercentPercentVo);
        vos.add(interactieVideoPercentPercentVo);
        vos.add(resourcePercentPercentVo);
        // vos.add(attendancePercentVo);

        return vos;
    }

    @Override
    public String calculateFinishedRateReturnInteger(StudentAnalysisContentResultDTO result) {
        List<StudyAnalysisVo> vos = new ArrayList<>();
        //计算所有数量
        Integer sum = 0;
        Integer finishSum = 0;
        //计算总数
        Integer homeworkPublishNum = result.getHomeworkPublishNum();
        Integer examPublishNum = result.getExamPublishNum();
        Integer discussPublishNum = result.getDiscussPublishNum();
        Integer attendancePublishNum = result.getAttendancePublishNum();
        Integer interactieCoursePublishNum = result.getInteractieCoursePublishNum();
        Integer interactieVideoPublishNum = result.getInteractieVideoPublishNum();
        Integer resoucePublishNum = result.getResoucePublishNum();
        Integer noticePublishNum = result.getNoticePublishNum();
        sum = homeworkPublishNum + examPublishNum + discussPublishNum + attendancePublishNum + interactieCoursePublishNum + interactieVideoPublishNum + resoucePublishNum;
        //计算完成数

        //作业完成率
        Integer homeworkFinishedNum = result.getHomeworkFinishedNum();
        //测评完成率
        Integer examFinishedNum = result.getExamFinishedNum();
        //讨论完成率
        Integer discussFinishedNum = result.getDiscussFinishedNum();
        //公告页面暂时未显示
        Integer noticeFinishedNum = result.getNoticeFinishedNum();
        //互动课件完成率
        Integer interactieCourseFinishedNum = result.getInteractieCourseFinishedNum();
        //互动视频完成率
        Integer interactieVideoFinishedNum = result.getInteractieVideoFinishedNum();

        //资料完成率
        Integer resouceFinishedNum = result.getResouceFinishedNum();
        //出勤完成率
        Integer attendanceFinishedNum = result.getAttendanceFinishedNum();

        //整体完成率
        finishSum = homeworkFinishedNum + examFinishedNum + discussFinishedNum + interactieCourseFinishedNum + interactieVideoFinishedNum + resouceFinishedNum + attendanceFinishedNum;
        String wholePercent = calculatePercent(finishSum, sum);
        return wholePercent;
    }

    private List<StudentAnalysisContentResultDTO> sorWholeFinishedRates(List<StudentAnalysisContentResultDTO> results, StudentAnalysisQueryDTO analysisQueryDTO) {
        if (results != null && results.size() > 0) {
            if (StringUtils.isNotEmpty(analysisQueryDTO.getSort())) {
                String sort = analysisQueryDTO.getSort();
                String underscore = camelCaceToUnderscore(sort);
                if (underscore.contains("whole_finished_rate desc")) {
                    List<StudentAnalysisContentResultDTO> collect = results.stream().sorted((o1, o2) ->
                        -(int) (Double.parseDouble(o1.getWholeFinishedRate()) - Double.parseDouble(o2.getWholeFinishedRate()))
                    ).collect(Collectors.toList());
                    return collect;
                }
                if(underscore.contains("whole_finished_rate asc")){
                    List<StudentAnalysisContentResultDTO> collect = results.stream().sorted((o1, o2) ->
                        (int) (Double.parseDouble(o1.getWholeFinishedRate()) - Double.parseDouble(o2.getWholeFinishedRate()))
                    ).collect(Collectors.toList());
                    return collect;
                }
            }
        }
        return results;
    }

    private StudyAnalysisVo buildStudyAnalysisVo(String count, Integer type) {
        StudyAnalysisVo vo = new StudyAnalysisVo();
        vo.setCount(Objects.isNull(count) ? "0" : count);
        vo.setType(type);
        return vo;
    }

    /**
     * 校验是否需老师统计信息
     * @param classId 班级ID
     * @description 目前：定时时间 每晚12点生成一次
     * @Author dzy
     */
    @Override
    public void checkCreateAnalysis(Long classId) {
        LambdaQueryWrapper<CourseAnalysisEntity> wrapper = new LambdaQueryWrapper();
        wrapper.eq(CourseAnalysisEntity::getClassId, classId)
        .last("LIMIT 1");
        CourseAnalysisEntity entity = analysisMapper.selectOne(wrapper);
        if (Objects.isNull(entity)) {
            // 生成总汇总信息
            analysisService.createAnalysis(classId);
            // 生成学生总汇总信息
            studentAnalysisService.createStudentAnalysis(classId);
        } else if (Duration.between(entity.getCreateTime(), LocalDateTime.now()).toDays() == 1) {
            // 生成总汇总信息
            analysisService.createAnalysis(classId);
            // 生成学生总汇总信息
            studentAnalysisService.createStudentAnalysis(classId);
        }
    }

    /**
     * 定时生成考勤数据
     * @description 目前：定时时间 每晚12点生成一次
     * @Author dzy
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void timingCreateAnalysis() {
        // 清空学情总统计信息
        analysisService.clearAnalysis();
        // 清空学情学生总统计信息
        studentAnalysisService.clearStudentAnalysis();
        // 查询班级信息
        List<ClassResultDTO> classList = R.as(classClient.findAllClass());

        // 遍历更新班级的统计信息
        classList.forEach(item -> {
            // 生成总汇总信息
            analysisService.createAnalysis(item.getId());
            // 生成学生总汇总信息
            studentAnalysisService.createStudentAnalysis(item.getId());
        });
    }

    /**
     * 导出学生学习记录
     * @description 目前：定时时间 每晚12点生成一次
     * @Author dzy
     */
    @Override
    public void studyAnalysisExport(StudyAnalysisExportDTO exportDTO, HttpServletResponse response) {
        //获取课程详情
        CourseResultDTO courseEntity = R.as(courseClient.findCourse(exportDTO.getCourseId()));
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(courseEntity), "未获取到数据");
        List<StudentAnalysisContentResultDTO> analysisList = this.baseMapper.StudyAnalysisExport(exportDTO);
        try {
            ClassPathResource cpr = new ClassPathResource("/excel/" + "学情分析.xlsx");
            InputStream is = cpr.getInputStream();
            Workbook workbook = new XSSFWorkbook(is);
            //居中设置
            CellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setAlignment(HorizontalAlignment.CENTER);
            Sheet sheet0 = workbook.getSheetAt(0);
            //为第二行设置值
            Row sheet0Row = sheet0.getRow(1);
            Cell cell = sheet0Row.getCell(0);
            cell.setCellValue("课程名称:"+courseEntity.getCourseName());
            for (int i = 0; i < analysisList.size(); i++) {
                Row row = sheet0.createRow(i + 3);
                Cell cell0 = row.createCell(0);
                cell0.setCellStyle(ExcelUtil.allFrame(workbook));

                Cell cell1 = row.createCell(1);
                cell1.setCellStyle(ExcelUtil.allFrame(workbook));

                Cell cell2 = row.createCell(2);
                cell2.setCellStyle(ExcelUtil.allFrame(workbook));

                Cell cell3 = row.createCell(3);
                cell3.setCellStyle(ExcelUtil.allFrame(workbook));

                Cell cell4 = row.createCell(4);
                cell4.setCellStyle(ExcelUtil.allFrame(workbook));

                Cell cell5 = row.createCell(5);
                cell5.setCellStyle(ExcelUtil.allFrame(workbook));

                Cell cell6 = row.createCell(6);
                cell6.setCellStyle(ExcelUtil.allFrame(workbook));

                Cell cell7 = row.createCell(7);
                cell7.setCellStyle(ExcelUtil.allFrame(workbook));
                // Cell cell8 = row.createCell(8);
                // Cell cell9 = row.createCell(9);
                //为单元格设置值
                StudentAnalysisContentResultDTO resultDTO = analysisList.get(i);
                cell0.setCellValue(resultDTO.getNickname());
                cell1.setCellValue(resultDTO.getStudentNumber()==null?"":resultDTO.getStudentNumber());
                //设置整体完成率
                String wholeRage = this.calculateFinishedRateReturnInteger(resultDTO);
                cell2.setCellValue(wholeRage + "%");
                //作业完成率
                String homeworkRate = calculatePercent(resultDTO.getHomeworkFinishedNum(), resultDTO.getHomeworkPublishNum());
                cell3.setCellValue(homeworkRate + "%");
                //测评完成率
                String examRate = calculatePercent(resultDTO.getExamFinishedNum(), resultDTO.getExamPublishNum());
                cell4.setCellValue(examRate + "%");
                //讨论完成率
                String discussRate = calculatePercent(resultDTO.getDiscussFinishedNum(), resultDTO.getDiscussPublishNum());
                cell5.setCellValue(discussRate + "%");
                //互动课件完成率
                // String interactiveCourseRate = calculatePercent(resultDTO.getInteractieCourseFinishedNum(), resultDTO.getInteractieCoursePublishNum());
                // cell6.setCellValue(interactiveCourseRate + "%");
                // 互动视频完成率
                String interactiveVideoeRate = calculatePercent(resultDTO.getInteractieVideoFinishedNum(), resultDTO.getInteractieVideoPublishNum());
                cell6.setCellValue(interactiveVideoeRate + "%");
                //资料完成率
                String resourceRate = calculatePercent(resultDTO.getResouceFinishedNum(), resultDTO.getResoucePublishNum());
                cell7.setCellValue(resourceRate + "%");
                //考勤完成率
                // String attendanceRate = calculatePercent(resultDTO.getAttendanceFinishedNum(), resultDTO.getAttendancePublishNum());
                // cell9.setCellValue(attendanceRate + "%");

            }
            ExcelUtil.downLoadExcel("学情分析", response, workbook);
            log.debug("学情分析导出结束-------------------------------------------------------");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String calculatePercent(Integer num1, Integer num2) {
        double wholeRate = 0.0;
        if (num2 != 0) {
            wholeRate = (double)num1 * 100 / num2;
        }
        String strNum = MathUtils.stripTrailingZeros(new BigDecimal(wholeRate), 1).toString();
        return strNum;
    }

}
